package com.ruby.bigtable.spark;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.streaming.Durations;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaPairDStream;
import org.apache.spark.streaming.api.java.JavaPairReceiverInputDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;
import org.apache.spark.streaming.kafka.KafkaUtils;

import scala.Tuple2;


public class WordCountKafkaStream {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SparkConf conf = new SparkConf().setMaster("local[2]").setAppName("Word Count");
		JavaStreamingContext jssc = new JavaStreamingContext(conf, Durations.seconds(5));
		
		Map<String, Integer> topicThreadMap = new HashMap<String, Integer>();
		topicThreadMap.put("test", 1);
		JavaPairReceiverInputDStream<String, String> lineDStream = KafkaUtils.createStream(jssc, "127.0.0.1:2181", "Default Consumer", topicThreadMap);
		
		JavaDStream<String> wordRdd = lineDStream.flatMap(new FlatMapFunction<Tuple2<String,String>, String>() {

			private static final long serialVersionUID = 1L;

			public Iterable<String> call(Tuple2<String, String> t) throws Exception {
				// TODO Auto-generated method stub
				return Arrays.asList(t._2.split(" "));
			}
		});
		
		JavaPairDStream<String, Integer> wordPair = wordRdd.mapToPair(new PairFunction<String, String, Integer>() {

			private static final long serialVersionUID = 1L;

			public Tuple2<String, Integer> call(String t) throws Exception {
				// TODO Auto-generated method stub
				return new Tuple2<String, Integer>(t, 1);
			}
		});
		
		JavaPairDStream<String, Integer> resRdd = wordPair.reduceByKey(new Function2<Integer, Integer, Integer>() {
			
			public Integer call(Integer v1, Integer v2) throws Exception {
				// TODO Auto-generated method stub
				return v1+v2;
			}
		});
		
		resRdd.print();
		
		jssc.start();
		jssc.awaitTermination();
		jssc.stop();
	}

}
